package com.eims.sls_app.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.CircleBean;
import com.eims.sls_app.dataaccess.CircleBean.CommentBean;
import com.eims.sls_app.dataaccess.CircleBean.SchemeinfoBean;
import com.eims.sls_app.dataaccess.CircleBean.SchemeinfoBean.InformationIdBean;
import com.eims.sls_app.dataaccess.CircleBean.TopicBean;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.adapter.CircleAdapterMy;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.RequestUtil;

import com.eims.sls_app.view.MyToast;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.socialize.media.GooglePlusShareContent;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;

import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CircleFragment_cirFrament_my extends Fragment {
	private String TAG = "CircleFragmentmy";
	private Activity activity;
	private PullToRefreshListView circle_item_listView;
	private TextView circle_item_hint;
	private String opt, auth, info, time, imei, crc; // 格式化后的参数

	private MyHandler mHandler;
	private MyAsynTask mMyAsynTask;
	private MySingleton mySingleton;
	private CircleBean circleBean;
	private InformationIdBean informationIdBean;
	private CircleAdapterMy circleAdapter;
	private boolean isToFirst = true;

	private ProgressDialog pd;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_circle_zq_circle, container, false);
		activity = getActivity();
		SharedPreferences myAhare = activity.getSharedPreferences("pinglun", Activity.MODE_PRIVATE);
		// 实例化SharedPreferences.Editor对象（第二步）
		SharedPreferences.Editor editor = myAhare.edit();
		// 用putString的方法保存数据
		editor.putInt("isfr", 0);

		editor.commit();

		mHandler = new MyHandler();
		Log.e("11", "11");
		init(view);
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		Log.e("time1", "onResume");

		SharedPreferences sharedPreferences = activity.getSharedPreferences("pinglun", Activity.MODE_PRIVATE);
		// 使用getString方法获得value，注意第2个参数是value的默认值

		int size = sharedPreferences.getInt("size", 1);
		if (size == 2) {
			int isfo = sharedPreferences.getInt("isfr", 0);
			if (isfo == 1) {
				int myuid = sharedPreferences.getInt("uid", 0);
				int myposition = sharedPreferences.getInt("position", 0);
				int myid = sharedPreferences.getInt("id", 0);
				int mycid = sharedPreferences.getInt("cid", 0);
				String mydetail = sharedPreferences.getString("detail", "");
				String mytime = sharedPreferences.getString("time", "");
				String myname = sharedPreferences.getString("name", "");
				String mydatetime = sharedPreferences.getString("datetime", "");
				String myrid =sharedPreferences.getString("rid", "");
				String myrname =sharedPreferences.getString("rname", "");
				String myruid =sharedPreferences.getString("ruid", "");
				CommentBean commentBean = new CommentBean();
				commentBean.id = myid;
				commentBean.cid = mycid;
				commentBean.uid = myuid;
				commentBean.detail = mydetail;
				commentBean.time = mytime;
				commentBean.name = myname;
				commentBean.datetime = mydatetime;
				commentBean.rid = myrid;
				commentBean.rname = myrname;
				commentBean.ruid = myruid;
				circleAdapter.setComm(myposition, commentBean);
				ProgressDialogBar.stopProgress();
				Log.e(TAG, commentBean.toString());
			}

			SharedPreferences myAhare = activity.getSharedPreferences("pinglun", Activity.MODE_PRIVATE);
			// 实例化SharedPreferences.Editor对象（第二步）
			SharedPreferences.Editor editor = myAhare.edit();
			// 用putString的方法保存数据
			editor.putInt("isfr", 0);

			editor.commit();
			
		}

		super.onResume();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void init(View view) {
		// pd = BaseHelper.showProgress(activity, "", "加载中...", true, false);
		mySingleton = MySingleton.getInstance(activity);
		circle_item_listView = (PullToRefreshListView) view.findViewById(R.id.circle_item_listView);
		circle_item_hint = (TextView) view.findViewById(R.id.circle_item_hint);

		info = AppTools.getDaString();
		MyAsynTask myAsynTask = new MyAsynTask();
		myAsynTask.execute();

		// circle_item_listView.onRefreshComplete();
		circle_item_listView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				circle_item_listView.getLoadingLayoutProxy(true, false)
						.setLastUpdatedLabel("最近更新: " + LotteryUtils.Long2DateStr_detail(System.currentTimeMillis()));
				// informations.clear();
				isToFirst = true;
				info = AppTools.getDaString();
				if (circleBean != null) {
					if (circleBean.topic != null) {
					if (circleBean.topic.size() != 0) {
						circleBean.topic.clear();
						circleBean.schemeinfo.clear();
					}
					circleAdapter.notifyDataSetChanged();
					}
				}

				MyAsynTask myAsynTask = new MyAsynTask();
				myAsynTask.execute();
				circle_item_listView.postDelayed(new Runnable() {

					@Override
					public void run() {

						circle_item_listView.onRefreshComplete();
					}
				}, 1000);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				// MyToast.getToast(getActivity(), "最后一个").show();
				if (circleBean.topic.size() < 10) {
					// MyToast.getToast(getActivity(), "这是最后一页了").show();

					circleAdapter.notifyDataSetChanged();
					circle_item_listView.postDelayed(new Runnable() {

						@Override
						public void run() {

							circle_item_listView.onRefreshComplete();
						}
					}, 1000);
				} else {

					info = circleBean.topic.get(9).datetime;

					circleAdapter.notifyDataSetChanged();
					mMyAsynTask = new MyAsynTask();
					mMyAsynTask.execute();
					circle_item_listView.postDelayed(new Runnable() {

						@Override
						public void run() {

							circle_item_listView.onRefreshComplete();
						}
					}, 1000);

				}
			}
		});

		/*
		 * circle_item_listView.setOnItemClickListener(new OnItemClickListener() {
		 * 
		 * @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		 * long arg3) {
		 * 
		 * MyToast.getToast(getActivity(), arg2+"hang").show(); } });
		 */

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}

	class MyAsynTask extends AsyncTask<Integer, Integer, String> {

		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {

			opt = "92";
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(getActivity());
			// info = RspBodyBaseBean.change_TheSun(schemeId+"", context_Sun);

			// String key = MD5.md5(AppTools.user.getUserPass() + AppTools.MD5_key);
			String key = App.key;
			if (App.user == null) {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info, "-1");
				auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");
			} else {
				crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
				auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			}

			String[] values = { opt, auth, info };
			Log.i(TAG, "晒单" + RequestParams.convertParams(getActivity(), opt, info));
			String result = HttpUtils.doPost(App.names, values, App.path);
			Log.e(TAG, "晒单：" + result);
			System.out.println("晒单：" + result);
			if ("-500".equals(result)) {
				return "-500";
			}

			circleBean = new CircleBean();
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONArray topic =  jsonObject.getJSONArray("topic");
				List<TopicBean> topicBeans = new ArrayList<CircleBean.TopicBean>();
				if (topic.equals("[]")) {
					error = "1";
				}
				for (int i = 0; i < topic.length(); i++) {

					JSONObject obj = topic.getJSONObject(i);
					TopicBean topicBean = new TopicBean();
					topicBean.id = obj.optInt("id");
					topicBean.userid = obj.optInt("userid");
					topicBean.detail = obj.optString("detail");
					topicBean.schemeid = obj.optInt("schemeid");
					topicBean.up = obj.optString("up");
					topicBean.datetime = obj.optString("datetime");
					topicBean.enable = obj.optBoolean("enable");
					topicBean.yjjj = obj.optString("yjjj");
					topicBean.stoptime = obj.getString("stoptime");
					topicBean.cancopy = obj.getBoolean("cancopy");
					topicBean.name = obj.optString("name");
					topicBean.HeadUrl = obj.optString("HeadUrl");
					topicBean.Wins = obj.optString("Wins");
					topicBean.iswin = obj.optString("iswin");
					topicBean.interest = obj.optString("interest");
					topicBean.PlayTypeID = obj.optString("PlayTypeID");
					topicBean.hb = obj.optString("hb");
					topicBean.follCount = obj.optString("follCount");
					topicBeans.add(topicBean);
				}
				JSONArray comment = jsonObject.getJSONArray("comment");
				List<List<CommentBean>> commentBeans = new ArrayList<List<CommentBean>>();
				for (int i = 0; i < comment.length(); i++) {
					JSONArray jsonArray = comment.getJSONArray(i);
					List<CommentBean> commentBeanlists = new ArrayList<CircleBean.CommentBean>();
					for (int j = 0; j < jsonArray.length(); j++) {
						JSONObject object2 = jsonArray.getJSONObject(j);
						CommentBean commentBean = new CommentBean();
						commentBean.id = object2.optInt("id");
						commentBean.cid = object2.optInt("cid");
						commentBean.uid = object2.optInt("uid");
						commentBean.detail = object2.optString("detail");
						commentBean.time = object2.optString("time");
						commentBean.name = object2.optString("name");
						commentBean.datetime = object2.optString("datetime");
						commentBean.rname = object2.optString("rname");
						commentBean.rid = object2.optString("rid");
						commentBean.ruid = object2.optString("ruid");
						commentBeanlists.add(commentBean);
					}
					commentBeans.add(commentBeanlists);
				}

				JSONArray schemeinfo = jsonObject.getJSONArray("schemeinfo");
				List<SchemeinfoBean> schemeinfoBeans = new ArrayList<CircleBean.SchemeinfoBean>();
				for (int i = 0; i < schemeinfo.length(); i++) {
					JSONObject object = schemeinfo.getJSONObject(i);
					SchemeinfoBean schemeinfoBean = new SchemeinfoBean();
					schemeinfoBean.buymoney = object.optString("buymoney");
					schemeinfoBean.buyTime = object.optString("buyTime");
					schemeinfoBean.preBetType = object.optString("preBetType");
					schemeinfoBean.isHide = object.optInt("isHide");
					schemeinfoBean.stopsellingtime = object.optString("stopsellingtime");
					schemeinfoBean.secretMsg = object.optString("secretMsg");
					schemeinfoBean.passTypeInfo = object.optString("passTypeInfo");
					// JSONArray optimization = object.getJSONArray("optimization");
					JSONArray InformationId = object.getJSONArray("informationId");
					List<InformationIdBean> informationIdBeans = new ArrayList<CircleBean.SchemeinfoBean.InformationIdBean>();
					for (int j = 0; j < InformationId.length(); j++) {
						JSONObject jsonObject2 = InformationId.getJSONObject(j);
						informationIdBean = new InformationIdBean();
						informationIdBean.ID = jsonObject2.optString("ID");
						informationIdBean.SchemeID = jsonObject2.optString("SchemeID");
						informationIdBean.PlayType = jsonObject2.optString("PlayType");
						informationIdBean.MatchNumber = jsonObject2.optString("MatchNumber");
						informationIdBean.Game = jsonObject2.optString("Game");
						informationIdBean.MaiTeam = jsonObject2.optString("MaiTeam");
						informationIdBean.GuestTeam = jsonObject2.optString("GuestTeam");
						informationIdBean.StopSelling = jsonObject2.optString("StopSelling");
						informationIdBean.LetBile = jsonObject2.optString("LetBile");
						informationIdBean.Score = jsonObject2.optString("Score");
						informationIdBean.Results = jsonObject2.optString("Results");
						informationIdBean.PassType = jsonObject2.optString("PassType");
						informationIdBean.issue = jsonObject2.optString("issue");
						informationIdBean.Status = jsonObject2.optString("Status");
						informationIdBean.EndTime = jsonObject2.optString("EndTime");
						informationIdBean.investContent = jsonObject2.optString("investContent");
						informationIdBean.Content = jsonObject2.optString("Content");
						informationIdBean.MainLoseball = jsonObject2.optString("MainLoseball");
						informationIdBean.LetScore = jsonObject2.optString("LetScore");
						informationIdBean.BigSmallScore = jsonObject2.optString("BigSmallScore");
						informationIdBean.strresult = jsonObject2.optString("strresult");
						informationIdBeans.add(informationIdBean);

					}
					schemeinfoBean.informationId = informationIdBeans;
					schemeinfoBeans.add(schemeinfoBean);
				}
				circleBean.comment = commentBeans;
				circleBean.topic = topicBeans;
				circleBean.schemeinfo = schemeinfoBeans;
			} catch (JSONException e) {

				e.printStackTrace();
			}
			error = "0";
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			circle_item_hint.setVisibility(View.GONE);
			circle_item_listView.setMode(Mode.BOTH);
			mHandler.sendEmptyMessage(Integer.parseInt(result));
			circle_item_listView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (pd != null) {
				pd.dismiss();
			}
			try {
				ProgressDialogBar.stopProgress();
			} catch (Exception e) {
				// TODO: handle exception
			}
			switch (msg.what) {
			case 0:
				if (isToFirst) {
					circleAdapter = new CircleAdapterMy(getActivity(), circleBean.topic, circleBean.schemeinfo,
							circleBean.comment);
					circle_item_listView.setAdapter(circleAdapter);
				} else {
					circleAdapter.addDate(circleBean.topic, circleBean.schemeinfo, circleBean.comment);
				}
				// circleAdapter.setDate(circleBean.topic,
				// circleBean.schemeinfo,circleBean.comment);
				isToFirst = false;
				// Log.e(TAG, circleBean.comment.toString());
				circleAdapter.notifyDataSetChanged();
				if (circleBean.topic != null) {
					if (circleBean.topic.size() == 0) {
						circle_item_hint.setVisibility(View.VISIBLE);
						circle_item_hint.setText("没有更多数据");
						circle_item_listView.setMode(Mode.PULL_FROM_START);
					}
				}

				// MyToast.getToast(context, "晒单成功").show();

				break;
			case 1:
				circle_item_hint.setVisibility(View.VISIBLE);
				circle_item_hint.setText("没有数据");
				// MyToast.getToast(context, "重复晒单").show();
				break;
			case -1:
				circle_item_hint.setVisibility(View.VISIBLE);
				circle_item_hint.setText("没有数据");
				break;
			case -500:
				circle_item_hint.setVisibility(View.VISIBLE);
				circle_item_hint.setText("网络异常，请重新打开网络");

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	}

}
